package com.example.opengldemo._11_.test;

import android.opengl.GLES30;

import com.example.opengldemo.util.MatrixState;
import com.example.opengldemo.util.ShaderBuffer;
import com.example.opengldemo.util.ShaderHandle;
import com.example.opengldemo.util.ShaderUtil;
import com.example.opengldemo.util.ShapeFactory;

import java.nio.FloatBuffer;

public class TextureImage {

    String vertexShader = null ; ;
    String fragShader  = null ;

    FloatBuffer vertexBuffer ;
    FloatBuffer texcoorBuffer ;

    int vCount ;

    public TextureImage(TextureImageView view){
        initShader(view);
        initBufferData() ;
    }
    ShaderHandle shaderHandle ;
    ShaderBuffer shaderBuffer ;
    private void initShader(TextureImageView view) {
       vertexShader =  ShaderUtil.loadFromAssetsFile("mixing/vertex.sh" ,view.getResources() ) ;
       fragShader = ShaderUtil.loadFromAssetsFile("mixing/fragment.sh" , view.getResources());
       initHandle(ShaderUtil.createProgram(vertexShader  , fragShader));

    }

    private void initHandle(int mProgram) {
        shaderHandle = new ShaderHandle(mProgram);
    }

    public float UNIT_SIZE = 0.2f ;
    private void initBufferData(){
        float[] vertexArray = new float[]{
                -1f, 1f , 0 ,
                -1f , -1f , 0 ,
                1f , 1f , 0 ,
                1f , -1f , 0
        };
        vertexBuffer = ShapeFactory.getFloatBuffer(vertexArray) ;

        vCount = vertexArray.length /3 ;

        float[] texCoorArray = new float[]{
                0 , 0 ,
                0 , 1f ,
                1f , 0,
                1f , 1f
        };
        texcoorBuffer = ShapeFactory.getFloatBuffer(texCoorArray);

    }

    public void drawSelf(int textureID){

        GLES30.glUseProgram(shaderHandle.getProgram());

        GLES30.glVertexAttribPointer(shaderHandle.get_A_PositionHandle() , 3 , GLES30.GL_FLOAT , false , 3*4 , vertexBuffer);
        GLES30.glVertexAttribPointer(shaderHandle.get_A_TexCoorsHandle() , 2 , GLES30.GL_FLOAT , false , 2*4 , texcoorBuffer);
        GLES30.glUniformMatrix4fv(shaderHandle.get_U_MVPMatrixHandle() , 1 , false , MatrixState.getFinalMatrix() , 0);
        GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D , textureID);
        GLES30.glEnableVertexAttribArray(shaderHandle.get_A_TexCoorsHandle() );
        GLES30.glEnableVertexAttribArray(shaderHandle.get_A_PositionHandle());

        GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP  , 0 , vCount);

        GLES30.glDisableVertexAttribArray(shaderHandle.get_A_TexCoorsHandle());
        GLES30.glDisableVertexAttribArray(shaderHandle.get_A_PositionHandle());
    }
}


